/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbTradeStateHisModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`his_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '纪录id',
  //`type` int(3) NOT NULL DEFAULT '0' COMMENT '类型:10商品订单,20发票',
  //`trade_obj_id` bigint(20) NOT NULL COMMENT '订单id/发票id',
  //`state` int(3) NOT NULL DEFAULT '0' COMMENT '订单/发票状态: 参照订单/发票表',
  //`total_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '订单总金额（单位为rmb分）',
  //`user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
  //`desc` varchar(200) DEFAULT NULL COMMENT '备注信息',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL,
  //`del_flg` int(1) NOT NULL DEFAULT '0',


};
ItbTradeStateHisModel.prototype = new ItbBaseModel();

// 取得表名
ItbTradeStateHisModel.prototype.getTableName = function(){
    return 'itb_trade_state_his';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbTradeStateHisModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'his_id='+this.his_id;
}

/**
 * 复制商品订单记录（保留各状态时间点）
 */
ItbTradeStateHisModel.prototype.copyItemOrderHis = function(oldOrderId, newOrderId, newTotalFee, callback){

    var THIS = this;
    pool.pool.getConnection(function(err, connection) {

        var totalFee = Number(newTotalFee||'0')||0;

        var sql = ' INSERT INTO itb_trade_state_his'+
            ' (`type`, `trade_obj_id`, `state`, `total_fee`, `user_id`, `desc`, '+
            ' `create_time`, `update_time`, `update_by`) '+
            ' SELECT t.type, ' + newOrderId + ', t.state, '+ totalFee + ', t.user_id, t.desc, '+
            ' t.create_time, t.update_time, "SPLIT_PROC" '+
            ' FROM itb_trade_state_his t'+
            ' WHERE t.del_flg=0 and t.type=10 and t.trade_obj_id='+oldOrderId;

        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();

            if(error){
                console.log(error);
                return callback(error, null);
            }

            return callback(null, null);
        });
    });
};

//
/**
 * 取得订单纪录
 * 参数: type	类型:10商品订单,20发票
 * 参数: trade_obj_id	订单id/发票id
 * 参数: state	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'
 * 参数：callback：回调，参数如下：
 *          error:错误消息
 *          data: ItbTradeStateHisModel
 * */
ItbTradeStateHisModel.prototype.getLastHisOfOrder = function(type, trade_obj_id,state,  callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {

        var sql =
            " select * from ("+
            " select h.* "+
            " from itb_trade_state_his h "+
            " where h.del_flg=0 "+
            " and h.trade_obj_id= "+trade_obj_id+
            " and h.type= "+type+
            " and h.state ="+state+
            " order by h.create_time desc ) t "+
            " limit 0,1 ";
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();
            if(error){
                console.log(error);
                return callback(error,null);
            }
            if(!results || results.length==0){
                return callback(null, null);
            }

            return callback(null, results[0]);
        });
    });
}


// 根据用户地址id获取地址信息
ItbTradeStateHisModel.prototype.getAddressByAddressId = function(addrId, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {

        var sql =
            ' SELECT addr.*, '+
            ' 	area1.name as prov_name,  '+
            ' 	area2.name as city_name,  '+
            ' 	area3.name as dist_name '+
            ' FROM itb_address addr, '+
            ' 	itb_area area1, '+
            ' 	itb_area area2, '+
            ' 	itb_area area3 '+
            ' WHERE addr.addr_id=  '+addrId+
            ' AND addr.del_flg=0  '+
            ' and addr.prov = area1.id '+
            ' and area1.del_flg=0 '+
            ' and addr.city = area2.id '+
            ' and area2.del_flg=0 '+
            ' and addr.dist = area3.id '+
            ' and area1.del_flg=0 ';

        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();
            if(error){
                console.log(error);
                return callback(error,null);
            }
            if(!results || results.length==0){
                return callback(null, null);
            }

            return callback(null, results[0]);
        });
    });
}


// 根据order id获取地址信息
ItbTradeStateHisModel.prototype.getAddressByOrderId = function(orderId, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {

        var sql =
            ' SELECT addr.*, '+
            ' 	area1.name as prov_name,  '+
            ' 	area2.name as city_name,  '+
            ' 	area3.name as dist_name '+
            ' FROM itb_trade_order o,'+
            '   itb_address addr, '+
            ' 	itb_area area1, '+
            ' 	itb_area area2, '+
            ' 	itb_area area3 '+
            ' WHERE o.order_id='+orderId+
            ' AND addr.addr_id= o.addr_id '+
            ' AND addr.del_flg=0  '+
            ' and addr.prov = area1.id '+
            ' and area1.del_flg=0 '+
            ' and addr.city = area2.id '+
            ' and area2.del_flg=0 '+
            ' and addr.dist = area3.id '+
            ' and area1.del_flg=0 ';

        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();
            if(error){
                console.log(error);
                return callback(error,null);
            }
            if(!results || results.length==0){
                return callback(null, null);
            }

            return callback(null, results[0]);
        });
    });
}





// 导出
module.exports = ItbTradeStateHisModel;